<template>
  <div class="page-container">
    <!-- 顶部导航栏 -->
    <TopNav />

    <!-- 页面主体内容 -->

    <!-- 操作按钮区域 - 优化布局 -->
    <div class="action-bar">
      <el-row :gutter="15" align="middle">
        <!-- 搜索框 - 占据主要空间 -->
        <el-col :span="8">
          <el-input
            v-model="searchName"
            placeholder="请输入领导姓名"
            clearable
            style="width: 100%;"
          />
        </el-col>
        
        <!-- 按钮组 - 紧凑排列 -->
        <el-col :span="16" class="button-group">

          <el-button 
            type="info" 
            size="large" 
            icon="Search" 
            @click="handleSearch"
          >
            查询
          </el-button>

          <el-button 
            type="primary" 
            size="large" 
            icon="Download" 
            @click="showImportDialog"
          >
            导入
          </el-button>
          
          <el-button 
            type="success" 
            size="large" 
            icon="Plus" 
            @click="showAddDialog"
          >
            新增
          </el-button>
        </el-col>
      </el-row>
    </div>

    <div class="card-container">
      <div class="table-wrapper">
        <el-table :data="leaderInfroList" border class="full-height-table"
            :header-cell-style="{ background: '#f0f0f0' }" :row-class-name="tableRowClassName">
            <el-table-column prop="personnel_code" label="人员编码" align="center" width="130"></el-table-column>
            <el-table-column prop="unit_name" label="单位名称" align="center" width="180"></el-table-column>
            <el-table-column prop="department_name" label="部门名称" align="center" width="180"></el-table-column>
            <el-table-column prop="name" label="姓名" align="center" width="120"></el-table-column>
            <el-table-column prop="gender" label="性别" align="center" width="70"></el-table-column>
            <el-table-column prop="current_position" label="现任职务" align="center" width="200"></el-table-column>
            <el-table-column prop="nationality" label="民族" align="center" width="100"></el-table-column>
            <el-table-column prop="birth_date" label="出生日期" align="center" width="120"></el-table-column>
            <el-table-column prop="work_start_date" label="参加工作日期" align="center" width="150"></el-table-column>
            <el-table-column prop="position_level" label="职务级别" align="center" width="180"></el-table-column>
            <el-table-column prop="id_card_number" label="身份证号" align="center" width="210"></el-table-column>
            <el-table-column label="操作" align="center" fixed="right">
              <template #default="scope">
                <el-button 
                  size="small" 
                  :icon="Edit" 
                  @click="handleEdit(scope.row)" 
                />
                <el-button 
                  size="small" 
                  :icon="Delete" 
                  @click="handleDelete(scope.row.id)" 
                />
              </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
          <el-form :model="form" :rules="rules" ref="formRef">
            <!-- 第一列 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="人员编码" prop="personnel_code">
                  <el-input v-model="form.personnel_code" placeholder="请输入人员编码" />
                </el-form-item>
                <el-form-item label="单位名称" prop="unit_name">
                  <el-input v-model="form.unit_name" placeholder="请输入单位名称" />
                </el-form-item>
                <el-form-item label="部门名称">
                  <el-input v-model="form.department_name" placeholder="请输入部门名称" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="form.name" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="form.gender" placeholder="请选择性别">
                    <el-option label="男" value="男" />
                    <el-option label="女" value="女" />
                  </el-select>
                </el-form-item>
                <el-form-item label="出生日期">
                  <el-date-picker v-model="form.birth_date" type="date" placeholder="选择出生日期" />
                </el-form-item>
                <el-form-item label="民族">
                  <el-select v-model="form.nationality" placeholder="请选择民族" filterable>
                    <el-option 
                      v-for="ethnic in ethnic_groups" 
                      :key="ethnic" 
                      :label="ethnic" 
                      :value="ethnic" 
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="籍贯">
                  <el-input v-model="form.native_place" placeholder="请输入籍贯" />
                </el-form-item>
                <el-form-item label="出生地">
                  <el-input v-model="form.birth_place" placeholder="请输入出生地" />
                </el-form-item>
                <el-form-item label="健康状况">
                  <el-input v-model="form.health_status" placeholder="请输入健康状况" />
                </el-form-item>
                <el-form-item label="学历">
                  <el-select v-model="form.education_level" placeholder="请选择学历" filterable>
                    <el-option 
                      v-for="level in education_levels" 
                      :key="level" 
                      :label="level" 
                      :value="level" 
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="毕业学校">
                  <el-input v-model="form.graduate_school" placeholder="请输入毕业学校" />
                </el-form-item>
              </el-col>
              
              <!-- 第二列 -->
              <el-col :span="12">
                <el-form-item label="所学专业">
                  <el-input v-model="form.major_studied" placeholder="请输入所学专业" />
                </el-form-item>
                <el-form-item label="学习类型">
                  <el-select v-model="form.study_type" placeholder="请选择学习类型" filterable>
                    <el-option 
                      v-for="type in study_types" 
                      :key="type" 
                      :label="type" 
                      :value="type" 
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="现任职务">
                  <el-input v-model="form.current_position" placeholder="请输入现任职务" />
                </el-form-item>
                <el-form-item label="职务级别">
                  <el-input v-model="form.position_level" placeholder="请输入职务级别" />
                </el-form-item>
                <el-form-item label="参加工作日期">
                  <el-date-picker v-model="form.work_start_date" type="date" placeholder="选择参加工作日期" />
                </el-form-item>
                <el-form-item label="毕业日期">
                  <el-date-picker v-model="form.graduation_date" type="date" placeholder="选择毕业日期" />
                </el-form-item>
                <el-form-item label="政治面貌">
                  <el-select v-model="form.political_status" placeholder="请选择政治面貌" filterable>
                    <el-option 
                      v-for="status in political_statuses" 
                      :key="status" 
                      :label="status" 
                      :value="status" 
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="身份证号" prop="id_card_number">
                  <el-input v-model="form.id_card_number" placeholder="请输入身份证号" />
                </el-form-item>
                <el-form-item label="聘任职称">
                  <el-input v-model="form.appointment_title" placeholder="请输入聘任职称" />
                </el-form-item>
                <el-form-item label="个人履历">
                  <el-input 
                    v-model="form.resume" 
                    type="textarea" 
                    :rows="4" 
                    placeholder="请输入个人履历" 
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </template>
    </el-dialog>
        
    <!-- 导入Excel -->
    <el-dialog v-model="importDialogVisible" title="导入领导人员信息" width="40%">
          <el-upload
              class="upload-excel"
              action="#"
              :file-list="fileList"
              :auto-upload="false"
              :on-change="handleFileChange"
              accept=".xlsx,.xls"
              drag
                >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">仅支持.xlsx格式文件，需与模板字段一致</div>
            <div class="el-upload__tip" style="color: orangered;" slot="tip">（注意:请把Excel中的数字单元格设置为文本格式）</div>
          </el-upload>
          <template #footer>
            <el-button @click="importDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitImport">确认导入</el-button>
          </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { Delete, Edit } from '@element-plus/icons-vue';
import TopNav from './navmenu.vue'
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dbClient from '../../utils/database.js'
import * as XLSX from 'xlsx';

// 新增导入相关响应式数据
const importDialogVisible = ref(false);
const fileList = ref([]);
let selectedFile = null;

// 搜索相关响应式数据
const searchName = ref('');

// 分页相关响应式数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const ethnic_groups = import.meta.env.VITE_ETHNIC_GROUPS?.split(',') || [];
const education_levels = import.meta.env.VITE_EDUCATION_LEVELS?.split(',') || [];
const study_types = import.meta.env.VITE_STUDY_TYPES?.split(',') || [];
const political_statuses = import.meta.env.VITE_POLITICAL_STATUSES?.split(',') || [];
const dialogVisible = ref(false);
const dialogTitle = ref('');
const form = ref({
  personnel_code: '',
  unit_name: '',
  department_name: '',
  name: '',
  gender: '',
  birth_date: '',
  nationality: '',
  native_place: '',
  birth_place: '',
  work_start_date: '',
  health_status: '',
  appointment_title: '',
  education_level: '',
  graduate_school: '',
  major_studied: '',
  study_type: '',
  current_position: '',
  position_level: '',
  graduation_date: '',
  political_status: '',
  id_card_number: '',
  resume: ''
});
const formRef = ref(null);

const rules = {
  personnel_code: [
    { required: true, message: '请输入人员编码', trigger: 'blur' }
  ],
  unit_name: [
    { required: true, message: '请输入单位名称', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'blur' }
  ],
  id_card_number: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { 
      pattern: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, 
      message: '请输入正确的18位身份证号', 
      trigger: 'blur' 
    }
  ],
};

// 字段映射：Excel列名 -> 数据库表字段名
const fieldMap = {
  '人员编码': 'personnel_code',
  '单位名称': 'unit_name',
  '部门名称': 'department_name',
  '姓名': 'name',
  '性别': 'gender',
  '出生日期': 'birth_date',
  '民族': 'nationality',
  '籍贯': 'native_place',
  '出生地': 'birth_place',
  '参加工作日期': 'work_start_date',
  '健康状况': 'health_status',
  '聘任职称': 'appointment_title',
  '学历': 'education_level',
  '毕业学校': 'graduate_school',
  '所学专业': 'major_studied',
  '学习类型': 'study_type',
  '现任行政职务': 'current_position',
  '职务级别': 'position_level',
  '毕业日期': 'graduation_date',
  '政治面貌': 'political_status',
  '身份证号': 'id_card_number',
  '个人履历': 'resume'
};

// 问题线索数据（对应problem_clues_situation表）
const problemClues = ref([]);

// 处分处理数据（对应discipline_organization_punishment表）
const disciplinePunishments = ref([]);

const leaderInfroList = ref([]);

// 页面加载时获取数据
onMounted(async () => {
  await getLeaderInfroList();
  await getProblemClues();       // 加载问题线索数据
  await getDisciplinePunishments(); // 加载处分处理数据
});

// 获取问题线索数据
const getProblemClues = async () => {
  try {
    // 查询所有问题线索数据，包含后续判断需要的字段
    const data = await dbClient.query(`
      SELECT 
        accept_person_code, 
        impact_end_date, 
        disposal_method1_level1, 
        disposal_method2_level1 
      FROM problem_clues_situation
    `);
    problemClues.value = data;
  } catch (error) {
    console.error('获取问题线索数据失败:', error);
    ElMessage.error('获取问题线索数据失败: ' + error.message);
  }
};

// 获取处分处理数据
const getDisciplinePunishments = async () => {
  try {
    // 查询所有处分处理数据，包含后续判断需要的字段
    const data = await dbClient.query(`
      SELECT 
        involved_person_code, 
        impact_end_date 
      FROM discipline_organization_punishment
    `);
    disciplinePunishments.value = data;
  } catch (error) {
    console.error('获取处分处理数据失败:', error);
    ElMessage.error('获取处分处理数据失败: ' + error.message);
  }
};

// 获取领导人员列表（支持姓名查询）
const getLeaderInfroList = async () => {
  try {
    let query = 'SELECT * FROM leader_personnel_infro';
    let countQuery = 'SELECT COUNT(*) as total FROM leader_personnel_infro';

    let params = [];
    
    if (searchName.value && searchName.value.trim()) {
      // 使用模糊查询，匹配被反映人中包含搜索词的记录
      const whereClause = ' WHERE name LIKE ?'; // 添加空格修复语法错误
      query += whereClause;
      countQuery += whereClause;
      params.push(`%${searchName.value.trim()}%`);
    } 

    //添加排序
    query += ' ORDER BY id DESC';
    
    // 添加分页
    const offset = (pagination.value.currentPage - 1) * pagination.value.pageSize;
    query += ` LIMIT ${pagination.value.pageSize} OFFSET ${offset}`;

    // 获取总数
    const countResult = await dbClient.query(countQuery, params);
    pagination.value.total = countResult[0].total;

    const data = await dbClient.query(query, params);
    leaderInfroList.value = data;
  } catch (error) {
    console.error('获取领导人员基本信息列表失败:', error);
    ElMessage.error('获取领导人员基本信息列表失败: ' + error.message);
  }
};

// 红绿灯功能
// 其中：人员文件线索情况、受党纪处分和组织处理情况处于影响期内时，人员信息为红色标识；
// 问题线索表中处理情况的“处置方式1”有内容，“处置方式2”无内容或显示立案时为黄色标识；
// 其余情况为绿色标识。
// case.vue中具有领导人员红绿灯功能。
// 表结构说明：
// leader_personnel_infro中的personnel_code对应problem_clues_situation中的accept_person_code的，两者是一对多的关系。
// leader_personnel_infro中的personnel_code对应discipline_organization_punishment中的involved_person_code的，两者是一对多的关系。
// impact_end_date在problem_clues_situation和discipline_organization_punishment中都存在。
// 要求：
// personnel_code对应的所有impact_end_date中，存在大于等于当前日期的，人员信息为红色。
// personnel_code对应的problem_clues_situation表中disposal_method1_level1有内容，并且disposal_method2_level1无内容或者为内容“立案”时，人员信息为黄色。
// 红色优先，其次黄色，其余为绿色。
// 请在tableRowClassName中实现。仅给出修改的部分即可。

const tableRowClassName = ({ row }) => {
  const code = row.personnel_code;
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  // 检查红色条件：存在有效的impact_end_date
  const checkRedCondition = () => {
    // 检查problem_clues_situation表
    const hasClueRed = problemClues.value.some(clue => 
      clue.accept_person_code === code && 
      new Date(clue.impact_end_date) >= today
    );

    // 检查discipline_organization_punishment表
    const hasPunishmentRed = disciplinePunishments.value.some(punishment => 
      punishment.involved_person_code === code && 
      new Date(punishment.impact_end_date) >= today
    );

    return hasClueRed || hasPunishmentRed;
  };

  // 检查黄色条件
  const checkYellowCondition = () => {
    return problemClues.value.some(clue => 
      clue.accept_person_code === code && 
      !!clue.disposal_method1_level1 && 
      (!clue.disposal_method2_level1 || clue.disposal_method2_level1 === '立案')
    );
  };

  if (checkRedCondition()) {
    return 'red-light';
  } else if (checkYellowCondition()) {
    return 'orange-light';
  } else {
    return 'green-light';
  }
};

// 显示导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true;
  fileList.value = [];
  selectedFile = null;
};

// 选择文件变化时触发
const handleFileChange = (uploadFile) => {
  fileList.value = [uploadFile];
  selectedFile = uploadFile.raw;
};

// 提交导入数据
const submitImport = async () => {
  if (!selectedFile) {
    ElMessage.warning('请选择要导入的Excel文件');
    return;
  }

  try {
    // 解析Excel文件
    const fileReader = new FileReader();
    fileReader.readAsBinaryString(selectedFile);
    fileReader.onload = async (event) => {
  const workbook = XLSX.read(event.target.result, { type: 'binary' });
  const worksheet = workbook.Sheets[workbook.SheetNames[0]];
  const excelData = XLSX.utils.sheet_to_json(worksheet);

  if (excelData.length === 0) {
    ElMessage.warning('Excel文件中无数据');
    return;
  }

  // ========== 数据处理（字段映射 + 日期解析） ==========
  const importData = [];
  const dateFields = ['birth_date', 'work_start_date', 'graduation_date']; // 需要处理的日期字段

  for (const item of excelData) {
    const formattedItem = {};
    let isItemValid = true;

    // 1. 字段映射（Excel列名 → 数据库字段名）
    Object.keys(fieldMap).forEach(excelField => {
      const dbField = fieldMap[excelField];
      formattedItem[dbField] = item[excelField] || ''; // 空值默认转空字符串
    });

    // 2. 修复日期解析：处理 Excel 数字格式/文本格式日期
    dateFields.forEach(dbField => {
      const excelValue = formattedItem[dbField];
      if (!excelValue) return; // 空日期跳过

      try {
        let dateObj;
        // 情况1：Excel 数字格式日期（如 44927 → 2023-01-01）
        if (typeof excelValue === 'number') {
          // 正确方法：XLSX.SSF.parse_date_code(数字, 选项)
          const dateCode = XLSX.SSF.parse_date_code(excelValue, { date1904: false });
          dateObj = new Date(dateCode.y, dateCode.m - 1, dateCode.d); // 月份需-1（SSF返回1-12，Date用0-11）
        } 
        // 情况2：文本格式日期（如 "2023-10-01"、"2023/10/01"）
        else if (typeof excelValue === 'string') {
          dateObj = new Date(excelValue);
        } 
        // 情况3：不支持的格式（标记为无效数据）
        else {
          isItemValid = false;
          ElMessage.warning(`数据【${formattedItem.name}】的${dbField}字段格式无效（需数字或文本日期）`);
          return;
        }

        // 验证日期有效性（排除 Invalid Date）
        if (isNaN(dateObj.getTime())) {
          isItemValid = false;
          ElMessage.warning(`数据【${formattedItem.name}】的${dbField}字段日期无效（${excelValue}）`);
          return;
        }

        // 格式化为数据库要求的 YYYY-MM-DD
        formattedItem[dbField] = `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}-${String(dateObj.getDate()).padStart(2, '0')}`;
      } catch (error) {
        isItemValid = false;
        ElMessage.warning(`数据【${formattedItem.name}】的${dbField}字段解析失败：${error.message}`);
      }
    });

    // 在日期格式处理和数字格式处理之后，添加文本字段处理，2025.11.26
          const textFields = ['report_unit_code']; // 可以扩展其他需要强制转换为文本的字段
          textFields.forEach(dbField => {
              if (formattedItem[dbField] !== null && formattedItem[dbField] !== undefined) {
                formattedItem[dbField] = String(formattedItem[dbField]);
              }
            });

    // 3. 仅保留有效数据
    if (isItemValid) {
      importData.push(formattedItem);
    }
  }

  // ========== 后续逻辑不变（验证必填字段 + 批量导入） ==========
  // 验证必填字段（与表单规则一致：人员编码、单位名称、姓名、性别、身份证号）
  const requiredFields = ['personnel_code', 'unit_name', 'name', 'gender', 'id_card_number'];
const validData = importData.filter(item => {
  const hasAllRequired = requiredFields.every(field => {
    // 1. 取出当前字段值（可能是数字、字符串、null、undefined）
    const rawValue = item[field];
    
    // 2. 处理逻辑：
    // - 若值为 undefined/null → 视为空（不满足必填）
    // - 若值为其他类型 → 先转字符串（避免数字/布尔等类型报错），再去空格
    const processedValue = rawValue === undefined || rawValue === null 
      ? '' 
      : String(rawValue).trim();
    
    // 3. 验证：处理后的值不为空
    return processedValue !== '';
  });

  if (!hasAllRequired) {
    // 优化提示：显示具体缺少的字段，方便用户排查
    const missingFields = requiredFields.filter(field => {
      const rawValue = item[field];
      const processedValue = rawValue === undefined || rawValue === null 
        ? '' 
        : String(rawValue).trim();
      return processedValue === '';
    });
    ElMessage.warning(`数据【${item.name || '未知人员'}】缺少必填字段：${missingFields.join('、')}，已过滤`);
  }

  return hasAllRequired;
});

  const invalidCount = importData.length - validData.length;
  if (invalidCount > 0) {
    ElMessage.warning(`共${invalidCount}条数据无效（格式错误/缺少必填项），已过滤`);
  }

  if (validData.length === 0) {
    ElMessage.error('无有效数据可导入');
    return;
  }

  // 批量插入数据库（原逻辑不变）
  try {
    const fields = Object.values(fieldMap);
    const placeholders = fields.map(() => '?').join(',');
    const values = validData.map(item => fields.map(field => item[field]));

    // 调用数据库批量插入方法（确保 dbClient 有 batchInsert 或支持事务）
    await dbClient.batchInsert(
      `INSERT OR REPLACE INTO leader_personnel_infro (${fields.join(', ')}) VALUES (${placeholders})`,
      values
    );


    ElMessage.success(`成功导入${validData.length}条领导人员数据(新增或更新)`);
    importDialogVisible.value = false;
    getLeaderInfroList(searchName.value); // 重新加载列表，保持当前搜索状态
  } catch (dbError) {
    console.error('数据库导入失败:', dbError);
    ElMessage.error(`导入失败：${dbError.message}`);
  }
};
  } catch (error) {
    console.error('导入失败:', error);
    ElMessage.error('导入失败: ' + error.message);
  }
};

const handleSearch = () => {
  pagination.value.currentPage = 1; // 搜索时重置到第一页
  getLeaderInfroList();
};

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pagination.value.pageSize = newSize;
  pagination.value.currentPage = 1; // 页数大小改变时重置到第一页
  getLeaderInfroList();
};

// 处理当前页变化
const handleCurrentChange = (newPage) => {
  pagination.value.currentPage = newPage;
  getLeaderInfroList();
};

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增领导人员';
  form.value = {
    personnel_code: '',
    unit_name: '',
    department_name: '',
    name: '',
    gender: '',
    birth_date: '',
    nationality: '',
    native_place: '',
    birth_place: '',
    work_start_date: '',
    health_status: '',
    appointment_title: '',
    education_level: '',
    graduate_school: '',
    major_studied: '',
    study_type: '',
    current_position: '',
    position_level: '',
    graduation_date: '',
    political_status: '',
    id_card_number: '',
    resume: ''
  };
  dialogVisible.value = true;
};

// 显示编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑领导人员';
  
  // 将字符串日期转换为 Date 对象
  const processedData = { ...row };
  const dateFields = ['birth_date', 'work_start_date', 'graduation_date'];
  
  dateFields.forEach(field => {
    if (processedData[field]) {
      processedData[field] = new Date(processedData[field]);
    }
  });
  
  form.value = processedData;
  dialogVisible.value = true;
};

// 删除领导人员
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('是否要删除当前行数据？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await dbClient.delete('DELETE FROM leader_personnel_infro WHERE id = ?', [id]);
    ElMessage.success('删除成功');
    getLeaderInfroList(searchName.value);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败: ' + error.message);
    }
  }
};
// 提交表单
const submitForm = async () => {
  try {
    // 先进行表单验证
    await formRef.value.validate();
  } catch (error) {
    // 表单验证失败，直接返回，不执行后续操作
    console.log('表单验证失败:', error);
    return;
  }
  // 2. 处理表单数据：日期格式转换 + 提取字段/值
  const formData = { ...form.value };
  const dateFields = ['birth_date', 'work_start_date', 'graduation_date'];

    // 转换日期为 YYYY-MM-DD 字符串
  dateFields.forEach(field => {
    if (formData[field] instanceof Date) {
      formData[field] = `${formData[field].getFullYear()}-${String(formData[field].getMonth() + 1).padStart(2, '0')}-${String(formData[field].getDate()).padStart(2, '0')}`;
    }
  });

    // 3. 自动获取字段名（排除空值可选，按需添加）
  const fields = Object.keys(formData).filter(key => key !== 'id'); // 新增/编辑都排除id（更新时单独传）
  const values = fields.map(key => formData[key]);

  try {
    if (formData.id) {
      // 编辑：更新数据
      const setClause = fields.map(field => `${field} = ?`).join(', ');
      await dbClient.update(
        `UPDATE leader_personnel_infro SET ${setClause} WHERE id = ?`,
        [...values, formData.id]
      );
      ElMessage.success('更新成功');
    } else {
      // 新增：插入数据
      const placeholders = fields.map(() => '?').join(',');
      await dbClient.insert(
        `INSERT INTO leader_personnel_infro (${fields.join(', ')}) VALUES (${placeholders})`,
        values
      );
      ElMessage.success('新增成功');
    }

    dialogVisible.value = false;
    getLeaderInfroList(searchName.value); // 重新加载列表，保持当前搜索状态
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败: ' + error.message);
  }
};
</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f6f7;
}

.card-container {
  flex: 1;
  padding: 20px;
  box-sizing: border-box;
}

/* 卡片：占满容器高度 */
.full-height-card {
  height: 99%;
  display: flex;
  flex-direction: column;
  background: #f5f6f7; /* 浅灰色背景 */
  margin: 10px;

}

/* 头部区域 */
:deep(.el-card__header) {
  min-height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  flex-shrink: 0;
  background: white;
}

/* 卡片主体内容区域：占据剩余空间 */
:deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  background: #f5f6f7; /* 浅灰色背景 */
}

/* 表格容器：自适应高度 + 滚动机制 */
.table-wrapper {
  margin: 20px 20px;
  background: white; /* 表格区域白色背景 */
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  max-height: calc(100vh - 300px); /* 计算可用高度（减去导航栏、卡片头和按钮栏的高度） */
  overflow-y: auto; /* 垂直滚动 */
}

/* 表格：自适应高度 */
.full-height-table {
  width: 100%;
}

/* 底部按钮区域 */
:deep(.el-card__footer) {
  min-height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  border-top: 1px solid #eee;
  flex-shrink: 0;
  background: white;
}

.action-buttons {
  display: flex;
  justify-content: flex-first;
  gap: 10px;
  width: 100%;
  margin: 10px;
}

/* 表头字体加粗样式 */
:deep(.el-table__header th .cell) {
  font-weight: bold;
  font-size: 18px;
  color: #1d1d1da9;
}

:deep(.el-table__body td .cell) {
  font-size: 18px;
}

/* 操作按钮区域样式 */
.action-bar {
  margin: 15px 15px 15px 15px;
  padding: 5px;
  /* background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); */
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  align-items: center;
}

/* 输入框样式调整 */
:deep(.el-input__wrapper) {
  width: 100%;
}

/* 按钮样式优化 */
.action-bar .el-button {
  min-width: 100px;
  height: 40px;
  font-size: 16px;
  font-weight: 500;
}

/* 搜索框样式优化 */
.action-bar .el-input {
  margin-right: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .action-bar .el-row {
    flex-direction: column;
    gap: 15px;
  }
  
  .action-bar .el-col {
    width: 100%;
  }
  
  .button-group {
    justify-content: center;
  }
}

/* 卡片容器间距调整 */
.card-container {
  flex: 1;
  padding: 10px 20px 20px 20px;
  box-sizing: border-box;
}

/* 表格容器间距调整 */
.table-wrapper {
  margin: 10px 0;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 16px;
  background: white;
  border-top: 1px solid #ebeef5;
}

:deep .el-table .green-light{
  color:green;
}
:deep .el-table .orange-light{
  color:orange;
}
:deep .el-table .red-light{
  color:red;
}

</style>